package com.s2paganini.data 
{
	import com.s2paganini.events.SenderEvent;

	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLRequest;
	import flash.net.URLRequestMethod;
	import flash.net.URLVariables;	

	/**
	 * @author siLvio paganini | s2paganini.com
	 * @purpose LoadVars
	 */

	public class Sender extends EventDispatcher
	{
		private var urlRequest : URLRequest;
		private var urlLoader : URLLoader;
		private var urlVariables : URLVariables;

		function Sender(whichURL : String, _method : String)
		{
			urlRequest = new URLRequest(whichURL);
			
			urlLoader = new URLLoader();
			urlLoader.dataFormat = URLLoaderDataFormat.TEXT;
			
			urlVariables = new URLVariables();
			
			urlLoader.addEventListener(Event.COMPLETE, listenerSender);
			urlLoader.addEventListener(IOErrorEvent.IO_ERROR, listenerSenderError);
			
			urlRequest.method = (_method == "POST") ? URLRequestMethod.POST : URLRequestMethod.GET; 
		}

		private function listenerSenderError(event : IOErrorEvent) : void
		{
			var tempEvent : SenderEvent = new SenderEvent(SenderEvent.SEND_FAIL);
			dispatchEvent(tempEvent);
		}

		private function listenerSender(event : Event) : void
		{
			var tempEvent : SenderEvent = new SenderEvent(SenderEvent.SEND_SUCCESS);
			tempEvent._response = urlLoader.data;
			dispatchEvent(tempEvent);
		}

		public function setVariables(vars : Object) : void
		{
			for (var key:String in vars) {
				urlVariables[key] = vars[key];
			}
		}

		public function send() : void
		{
			urlRequest.data = urlVariables;
			//trace(urlRequest.data);
			urlLoader.load(urlRequest);
		}
	}
}
